package top.chenfu.security.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import top.chenfu.security.entity.Menu;
import top.chenfu.security.entity.Role;
import top.chenfu.security.service.MenuService;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther chenfu
 * @2019/10/29 13:47
 * @Desc
 */
@Component
public class CustomMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    /**
     * 根据当前请求路径，和数据库中的路径做匹配，查找访问该资源所需的全部角色
     *
     * @param o
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menus = menuService.getAllMenu();
        for (Menu menu : menus) {
            /**
             * 路径匹配查出当前路径所需要的角色返回
             */
            if (ANT_PATH_MATCHER.match(menu.getUrl(), requestUrl)) {
                List<Role> roles = menu.getRoles();
                return SecurityConfig.createList(roles.stream().filter(Objects::nonNull).map(Role::getName).distinct().toArray(String[]::new));
            }
        }
//        不匹配，设置为匿名访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}
